package sbpme.designer.command;

import java.util.List;

import org.eclipse.gef.commands.Command;

import sbpme.designer.model.Activity;
import sbpme.designer.model.Transition;

public class TransitionReconnectSourceCommand extends Command {

	protected Activity source;
	protected Activity target;
	protected Transition transition;
	protected Activity oldSource;

	public boolean canExecute() {
		if (transition.getTarget().equals(source))
			return false;

		List transitions = source.getTargetTransitions();
		for (int i = 0; i < transitions.size(); i++) {
			Transition trans = ((Transition) (transitions.get(i)));
			if (trans.getTarget().equals(target) && !trans.getSource().equals(oldSource))
				return false;
		}
		return true;
	}


	public void execute() {
		if (source != null) {
			oldSource.removeTargetTransition(transition);
			transition.setSource(source);
			source.addTargetTransition(transition);
		}
	}

	public void undo() {
		source.removeTargetTransition(transition);
		transition.setSource(oldSource);
		oldSource.addTargetTransition(transition);
	}

	public Activity getSource() {
		return source;
	}

	public Activity getTarget() {
		return target;
	}

	public Transition getTransition() {
		return transition;
	}

	public void setSource(Activity activity) {
		source = activity;
	}

	public void setTarget(Activity activity) {
		target = activity;
	}

	public void setTransition(Transition trans) {
		transition = trans;
		target = trans.getTarget();
		oldSource = trans.getSource();
	}

}
